package Exercise;

/**
 * 有三个线程，线程名称分别为：a，b，c。
 *
 * 每个线程打印自己的名称。
 *
 * 需要让他们同时启动，并按 c，b，a的顺序打印
 */


/**
 * 1.法1
 * 为了顺序调度，最好一开始就统统等待阻塞
 * wait 和 notify
 */
public class demo4 {

    static Object  locker1=new Object();
    static Object  locker2=new Object();
    static Object  locker3=new Object();
    public static void main(String[] args) throws InterruptedException {
        Thread thread1=new Thread(()->{
            synchronized (locker1){
                try {
                    locker1.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+" ");
                synchronized (locker2){
                    locker2.notify();
                }
            }

        },"c");
        Thread thread2=new Thread(()-> {
            synchronized (locker2){
                try {
                    locker2.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+" ");
                synchronized (locker3){
                    locker3.notify();
                }
            }

        },"b");
        Thread thread3=new Thread(()-> {
            synchronized (locker3){
                try {
                    locker3.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+" ");
            }

        },"a");

        thread1.start();
        thread2.start();
        thread3.start();

        Thread.sleep(1000);
        synchronized (locker1){
            locker1.notify();
        }

    }
}

/**
 * 2.法2
 * 用join
 */
class demo4_2{
    public static void main(String[] args) {
        Thread thread1=new Thread(()->{

                System.out.println(Thread.currentThread().getName()+" ");
        },"c");
        Thread thread2=new Thread(()-> {
            try {
                thread1.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" ");
        },"b");
        Thread thread3=new Thread(()-> {
            try {
                thread2.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" ");
        },"a");

        thread1.start();
        thread2.start();
        thread3.start();

    }

}
